package me.ahoukuse.capturedemov1;

import android.util.Log;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayDeque;
import java.util.Deque;

public class NetworkThreadTCP extends NetworkThread {
    private String server = "localhost";
    private int port = 2333;
    private Socket tcpSocket;
    private OutputStream out;
    private final Deque<byte[]> dataQueue = new ArrayDeque<>();
    private int packetId = 0;
    private int maxPacketDataLength = 65000;
    private void open() throws IOException {
        Log.d("Debug", "open: TCP");
        tcpSocket = new Socket(server, port);
        out = tcpSocket.getOutputStream();
    }

    public NetworkThreadTCP(String server, int port) {
        this.server = server;
        this.port = port;
    }
    public NetworkThreadTCP(String server) {
        this.server = server;
    }
    public NetworkThreadTCP() {

    }

    @Override
    public void addData(byte[] data) {
        synchronized (dataQueue) {
            if (!dataQueue.isEmpty()) {
                dataQueue.clear();
            }
            dataQueue.addLast(data);
            dataQueue.notify();
        }
    }
    private void socketClose() throws IOException {
        if (tcpSocket != null) {
            if (out != null)
                out.close();
            tcpSocket.close();
            Log.d("Debug", "Socket closed");
        }
    }
    private void send() throws IOException, InterruptedException {
        byte[] rawData;
        synchronized (dataQueue) {
            while (dataQueue.isEmpty()) {
                dataQueue.wait();
            }
            rawData = dataQueue.pop();
        }
        //特殊意义
        if (rawData.length == 0)
            return;
        Packet packet = new Packet();
        packet.setData(rawData);
        packet.setTotalLength(rawData.length);
        packet.setOffset(0);
        packet.setDataLength(rawData.length);
        packet.setPacket_id(packetId);
        //Log.d("Debug",  String.format("Sent totalLength:%d packet_id: %d offset %d PacketLength: %d",packet.getTotalLength(), packetId,packet.getOffset(), packet.getPacketLength()));
        out.write(packet.getBytes());
        out.flush();
        Log.d("Debug", String.format("packetId = %d", packetId));
        packetId++;
    }

    @Override
    public void run() {
        try {
            open();
            if (tcpSocket != null) {
                while (!isExit) {
                    send();
                }
            }
            socketClose();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            Log.d("Debug", "NetworkThreadTCP exit");

        }
    }
}
